﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using DomainModel.ClassMaps;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;

namespace DomainModel
{
    public class SessionProvider
    {
        private static object syncObj = new object();
        private static volatile ISessionFactory _sessionFactory;

        public static ISession NewSession
        {
            get
            {
                if (_sessionFactory == null)
                {
                    lock (syncObj)
                    {
                        if (_sessionFactory == null)
                        {
                            _sessionFactory = BuildSessionFactory();
                        }
                    }
                }
                return _sessionFactory.OpenSession();
            }
        }

        private static ISessionFactory BuildSessionFactory()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
            ISessionFactory factory =
                Fluently.Configure().Database(MsSqlConfiguration.MsSql2008.ShowSql().ConnectionString(connectionString))
                    .Mappings(
                        x => x.FluentMappings.AddFromAssemblyOf<UserClassMap>()).BuildSessionFactory();
            return factory;
        }
    }
}
